package com.news.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.news.client.NewsService;
import com.news.shared.GoogleNews;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class NewsServiceImpl extends RemoteServiceServlet implements NewsService{

	@Override
	public GoogleNews[] getNews(String cityname, String scoring, int numberOfResults) {
		try {
			String apiKey = "ABQIAAAAUatAjivAJ41Atlxr3K-hbhRA34sG9RIE2BYx69mpAes3xLwx-xRH8he8WD29KjlHC4ms4INDQDivGg";
		
			String apiURL = "https://ajax.googleapis.com/ajax/services/search/news?" +
					"v=1.0&rsz="+numberOfResults+"&q="+cityname+"&key=" + apiKey;
			
			String newsString = getJSONData(apiURL);
			System.out.println(newsString);
			JSONArray newsJSON = new JSONObject(newsString).getJSONObject("responseData").getJSONArray("results");
			
			GoogleNews[] news = new GoogleNews[newsJSON.length()];
			String title, content, url, imageurl = null;
			for (int i = 0; i < newsJSON.length(); i++){
				title = newsJSON.getJSONObject(i).getString("title");
				content = newsJSON.getJSONObject(i).getString("content");
				url = newsJSON.getJSONObject(i).getString("unescapedUrl");
				if (newsJSON.getJSONObject(i).has("image")){
					JSONObject img = new JSONObject(newsJSON.getJSONObject(i).getString("image"));
					imageurl = img.getString("tbUrl");
				}
				news[i] = new GoogleNews(title, content, url, imageurl);
			}
//			System.out.println("getNews called on server");
			return news;
			
		}catch(JSONException e){
			e.printStackTrace();
		}
		return null;
		
	}
	
	@Override
	public String[] getNearbyPlaces(String cityname) {
		
		String[] nearbyPlaces = getNearbyPlacesFromDatastore(cityname);
		if (nearbyPlaces == null){
			nearbyPlaces = getNearbyPlacesFromAPI(cityname);
		}
		return nearbyPlaces;
	}
	
	private String[] getNearbyPlacesFromDatastore(String cityname){
		
		return null;
	
	}
	
	private String[] getNearbyPlacesFromAPI(String cityname){
		try {
			String username = "anneceh";
			
			// First get latitude and longitude of city
			String apiURL = "http://api.geonames.org/searchJSON?q="+cityname+"&maxRows=10&username=" + username;			
			String resultString = getJSONData(apiURL);
			System.out.println(resultString);
			JSONArray cityJSON = new JSONObject(resultString).getJSONArray("geonames");
			long latitude, longitude;
			latitude = cityJSON.getJSONObject(0).getLong("lat");
			longitude = cityJSON.getJSONObject(0).getLong("lng");
			
			System.out.println("city: " + cityname + ", latitude: " + latitude + ", longitude: " + longitude);
			
			// Then get places within a 100 kilometer from that latitude and longitude
			apiURL = "http://api.geonames.org/findNearbyJSON?lat=" + 
				latitude + "&lng=" + longitude + "&radius=300&username="+username; 
			resultString = getJSONData(apiURL);
			System.out.println(resultString);
			JSONArray nearbyCitiesJSON = new JSONObject(resultString).getJSONArray("geonames");
			String[] cityNames = new String[nearbyCitiesJSON.length()];
			for (int i = 0; i < nearbyCitiesJSON.length(); i++){
				cityNames[i] = nearbyCitiesJSON.getJSONObject(i).getString("name");
			}
			
			return cityNames;
			
		}catch(JSONException e){
			e.printStackTrace();
		}
		return null;
	}
	
	private String getJSONData(String apiUrl) {
		StringBuilder json = new StringBuilder();
		try{
			URL url = new URL(apiUrl.replaceAll(" ", "%20"));
			URLConnection connection = url.openConnection();
			connection.addRequestProperty("referer", "http://localgwt.appspot.com");
	        BufferedReader in = new BufferedReader(
	                                new InputStreamReader(
	                                connection.getInputStream()));
	        String inputLine;
	        while ((inputLine = in.readLine()) != null){ 
	            json.append(inputLine.trim());
	        }
	        in.close();
		}catch(MalformedURLException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
		return json.toString();
	}

	

}
